const { SERVER_ERR, TOKEN_IS_TIMEOUT } = require("../config/error");
const userService = require("../service/user.service");
const { verifyToken: verifyTokenFn } = require("../utils/disposeToken");

const verifyToken = async (ctx, next) => {
  try {
    const { authorization = "" } = ctx.headers;
    const token = authorization.replace("Bearer ", "");
    const flag = verifyTokenFn(token);
    if (!flag) {
      ctx.app.emit("error", TOKEN_IS_TIMEOUT, ctx);
      return;
    }
    const res = await userService.detail(flag.id);
    ctx.user = res;
    await next();
  } catch (error) {
    ctx.error = error;
    ctx.app.emit("error", SERVER_ERR, ctx);
  }
};
module.exports = verifyToken;
